/* 
 * File:   Output.cpp
 * Author: Maximiliano Monzón (82341)
 * 
 * Created on October 12, 2012, 12:29 AM
 */

#include <iostream>
#include <fstream>
#include <cstring>
#include "Output.h"

using namespace std;
using namespace TP;

Output::Output() {
    this->stream = &cout;
}

Output::Output(int argc, char *argv[]) throw (int){
    
    this->stream = &cout;
    this->fileName = "?";
    
    if (argc > 2)
        this->fileName = argv[2];
}

Output::~Output() {
    this->Liberar();
}

ostream& Output::Stream() {
    return *this->stream;
            
}

void Output::Inicializar (){

    if (0 != strcmp (this->fileName.c_str(), "-"))
    {
        ofstream* file = new ofstream;
        file->open (this->fileName.c_str(), ofstream::out);

        if (file->is_open())
            this->stream = (ostream*) file;
        else
        {
            delete file;
            throw INIT_OUTPUT_FAIL;
        }
    }
}

void Output::Liberar (){

    if (this->stream)
        if (&cout != this->stream)
        {
            ((ofstream*) this->stream)->close();
            delete ((ofstream*) this->stream);
        } 
}
